package com.it.schoolhomeos.service.impl;

import com.it.schoolhomeos.entity.ClassInfo;
import com.it.schoolhomeos.entity.Student;
import com.it.schoolhomeos.repository.ClassInfoRepository;
import com.it.schoolhomeos.repository.StudentRepository;
import com.it.schoolhomeos.service.ClassService;
import com.it.schoolhomeos.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Transactional
public class ClassServiceImpl implements ClassService {

    @Autowired
    private ClassInfoRepository classInfoRepository;
    
    @Autowired
    private StudentRepository studentRepository;
    
    @Autowired
    private StudentService studentService;

    @Override
    public List<ClassInfo> findAll() {
        return classInfoRepository.findAll();
    }

    @Override
    public List<ClassInfo> findByKeyword(String keyword) {
        System.out.println("Service层接收到关键字: " + keyword);
        
        if (keyword == null || keyword.trim().isEmpty()) {
            System.out.println("关键字为空，返回所有班级");
            return findAll();
        }
        
        String trimmedKeyword = keyword.trim();
        System.out.println("执行关键字查询，处理后的关键字: " + trimmedKeyword);
        
        List<ClassInfo> results = classInfoRepository.findByKeyword(trimmedKeyword);
        System.out.println("查询结果数量: " + (results != null ? results.size() : 0));
        
        return results;
    }

    @Override
    public ClassInfo findById(Long id) {
        return classInfoRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("班级不存在: " + id));
    }

    @Override
    public ClassInfo save(ClassInfo classInfo) {
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        classInfo.setCreateTime(now);
        classInfo.setUpdateTime(now);
        
        return classInfoRepository.save(classInfo);
    }

    @Override
    public ClassInfo update(ClassInfo classInfo) {
        if (!classInfoRepository.existsById(classInfo.getId())) {
            throw new RuntimeException("班级不存在: " + classInfo.getId());
        }
        
        // 获取原有班级信息，保留创建时间
        ClassInfo existingClass = findById(classInfo.getId());
        classInfo.setCreateTime(existingClass.getCreateTime());
        
        // 设置更新时间
        classInfo.setUpdateTime(LocalDateTime.now());
        
        return classInfoRepository.save(classInfo);
    }

    @Override
    public void deleteById(Long id) {
        if (!classInfoRepository.existsById(id)) {
            throw new RuntimeException("班级不存在: " + id);
        }
        
        try {
            // 1. 获取班级对象
            ClassInfo classInfo = findById(id);
            
            // 2. 查找该班级下的所有学生
            List<Student> students = studentRepository.findByClassInfo(classInfo);
            
            // 3. 删除每个学生（使用 StudentService 的 deleteById 方法，确保级联删除学生的相关数据）
            if (students != null && !students.isEmpty()) {
                for (Student student : students) {
                    studentService.deleteById(student.getId());
                }
            }
            
            // 4. 最后删除班级
            classInfoRepository.deleteById(id);
        } catch (Exception e) {
            throw new RuntimeException("删除班级失败: " + e.getMessage(), e);
        }
    }
} 